package com.tarena.demo.luban.all.main.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.demo.luban.all.main.mapper.OrderMapper;
import com.tarena.demo.luban.all.main.service.OrderService;
import com.tarena.demo.luban.protocol.cart.param.CartDeleteParam;
import com.tarena.demo.luban.protocol.order.dos.OrderDO;
import com.tarena.demo.luban.protocol.order.param.OrderAddParam;
import com.tarena.demo.luban.protocol.stock.param.StockReduceCountParam;
import com.tarena.luban.demo.cart.api.CartApi;
import com.tarena.luban.demo.stock.api.StockApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired(required = false)
    private StockApi stockApi;
    @Autowired(required = false)
    private CartApi cartApi;
    @Autowired
    private OrderMapper orderMapper;
    @Override public void addOrder(OrderAddParam param) {
        //先查询订单是否存在 param携带了orderSn
        String orderSn=param.getOrderSn();
        //select count(*) from order_tbl where order_sn=#{orderSn};
        int total=orderMapper.countOrderByOrderSn(orderSn);
        if (total>0){
            //说明这个orderSn的订单已经存在
            return;
        }
        // 减库存
        StockReduceCountParam stockReduceCountParam=new StockReduceCountParam();
        stockReduceCountParam.setReduceCount(param.getCount());
        stockReduceCountParam.setProductCode(param.getProductCode());
        stockReduceCountParam.setOrderSn(param.getOrderSn());
        stockApi.reduceStock(stockReduceCountParam);
        //stockService.reduceCommodityCount(stockReduceCountParam);
        //增订单
        OrderDO orderDO=new OrderDO();
        BeanUtils.copyProperties(param,orderDO);
        orderMapper.insertOrder(orderDO);
        //删除购物车
        Entry entry=null;
        CartDeleteParam cartDeleteParam = new CartDeleteParam();
        cartDeleteParam.setUserId(param.getUserId());
        cartDeleteParam.setProductCode(param.getProductCode());
        try {
            entry= SphU.entry("orderAdd");
            //cartService.deleteCart(cartDeleteParam);
            cartApi.deleteCart(cartDeleteParam);
        }catch (BlockException ex){
            log.info("当前删除购物车逻辑出现异常:{},模拟当前数据记录日志:{}",ex.getClass().getName(),cartDeleteParam);
        }finally {
            if(entry!=null){
                entry.exit();
            }
        }
    }
}
